package com.lemon.datasource.provider;

import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.lemon.datasource.properties.DataSourceProperties;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 李猛
 * @datetime 2024/2/21 14:34
 * @description 类对象
 */
public class JdbcDynamicDataSourceProvider extends AbstractJdbcDataSourceProvider {
    private final DefaultDataSourceCreator creator;
    private final DataSourceProperties properties;

    public JdbcDynamicDataSourceProvider(DefaultDataSourceCreator creator, DataSourceProperties properties) {
        super(creator, properties.getDriverClassName(), properties.getUrl(), properties.getUsername(), properties.getPassword());
        this.creator = creator;
        this.properties = properties;
    }

    @Override
    protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
        ResultSet result = statement.executeQuery("select id,name,driver_class_name,url,username,password from dynamic_datasource where status = 1");
        Map<String, DataSourceProperty> map = new HashMap<>();
        while (result.next()) {
            String name = result.getString("name");
            String username = result.getString("username");
            String password = result.getString("password");
            String url = result.getString("url");
            DataSourceProperty property = new DataSourceProperty();
            property.setUsername(username);
            property.setLazy(true);
            property.setPassword(password);
            property.setUrl(url);
            map.put(name, property);
        }
        return map;
    }
}
